<template>
	<view class="content">
		<u-navbar :border-bottom="false"
				:is-back="true" 
				title="选择好友" 
				title-color="#000000" 
				title-bold  :title-size="36"
				:background="{ background:'#EDEDED'}"  :height="44">
			<view slot="right" class="u-p-r-30">
				<u-button v-if="selectedUser.size>0" type="success" size="mini" @click="launchChatGroup()">
				  <text class="u-font-30">完成({{selectedUser.size}})</text>
				</u-button>
				<u-button v-else  size="mini" disabled  :custom-style="customSendBtnStyle">完成</u-button>
			</view>
		</u-navbar>
		<view style="background-color:#EDEDED;">
			<view class="u-flex u-row-center u-col-center u-m-16 u-m-b-20"
					style="background-color:#FFFFFF;height: 80rpx;border-radius: 20rpx;">
				<view class="u-m-r-20">
					<u-icon class="u-clear-icon" top="6rpx"  :size="40" name="search" color="#909399"></u-icon>
				</view>
				<view style="color: #909399;font-size: 34rpx;">搜索</view>
			</view>
		</view>
		
		<view style="width: 100%;" v-show="myFirendList.length>0">
			<u-index-list :scrollTop="scrollTop"  active-color="#19be6b"  :index-list="indexList"  :offset-top="88">
				<view v-for="(item, index) in myFirendList" :key="index" style="width: 100%;">
					<u-index-anchor :index="item.firstLetter"/>
						<view v-for="friend in item.friends" :key="friend.id" class="list-cell">
							<view>
								<u-checkbox shape="circle" active-color="#19be6b" :size="40"
											@change="checkBoxChange"
											v-model="friend.isChecked" 
											:name="friend.friendId"
											:key="friend.friendId"></u-checkbox>
							</view>
							<view>
								<u-image :src="friend.headImg"  mode="aspectFill" width="80" height="80" border-radius="12">
									<view slot="error" class="u-flex u-row-center u-col-center">
										<u-image src="/static/image/default/default-user/default-user.png"  
										mode="aspectFill" width="60" height="60">
										</u-image>
									</view>
								</u-image>
							</view>
							<view  class="list-cell-name">{{friend.friendName?friend.friendName:friend.userName}}</view>
						</view>
				</view>
			</u-index-list>
		</view>
		
		<template v-if="groupInfoShowFlag">
			<create-group-pop ref="groupPop"
						:windowHeight="windowHeight"
						:groupModelFlag="groupInfoShowFlag"
						@submitCreate="submitCreate"
						@closeModel="closeModel"></create-group-pop>
		</template>
		
	</view>
</template>

<script>
import searchInput from '@/components/searchInput/index.vue';
import createGroupPop from '@/components/create-group-pop/create-group-pop.vue';
export default {
	components:{searchInput,createGroupPop},
	data() {
		return {
			customSendBtnStyle: { //发送按钮的自定义样式
				backgroundColor:'#AEAEB2',
				color:'#ffffff',
				fontSize:'30rpx'
			},
			scrollTop: 0,
			indexList:[],
			myFirendList:[],
			selectedUser:new Set(),
			currentUserId:'',
			groupInfoShowFlag:false,
			chatGroupName:'',
			windowHeight:0,
		
		};
	},

	created:function(){
		this.windowHeight=this.$u.sys().windowHeight;
	},
	
	onLoad:function(){
		let that=this;
		let userId= that.vuex_userInfo.id;
		that.currentUserId=userId;
		that.getMyFriendList();//获取通讯录好友
	},
	
	methods: {
		//初始化通讯录列表
		getMyFriendList:function(){
		   let that=this;
		   let param={};
		    that.$u.api.imUser.getMyFriendList(param).then(res => {
				if(res.code==200){
					let data=res.data;
					let indexList= data.myFriendsIndexList;
					if(indexList!=null&&indexList!=undefined){
						that.indexList=indexList;
					}
					let myFriendList= data.myFriendList;
					if(myFriendList!=null&&myFriendList!=undefined){
						that.myFirendList=myFriendList;
					}
				}
			})	   
		},
		
	    //监听选中人员
		checkBoxChange:function(e){
			let friendId= e.name;
			let isChecked=e.value;
			if(isChecked){
				this.selectedUser.add(friendId);
			}else{
				if(this.selectedUser.has(friendId)==true){
					this.selectedUser.delete(friendId);
				} 
			}
		},
	
		//发起群聊
		launchChatGroup:function(){
			let that=this;
			if(that.selectedUser.size<1){
				console.log("没有选中人员")
				return;
			}
			else{
				that.groupInfoShowFlag=true;
			}
		},
		closeModel:function(){
			that.groupInfoShowFlag=false;
		},
		submitCreate:function(newGroup){
			console.log("群信息",newGroup);
			this.buildChatGroup(newGroup);
		},
		buildChatGroup:function(newGroup){
			let that=this;
			let selectedFriends=[];
			that.selectedUser.forEach((item) => {
			  selectedFriends.push(item);
			})
			selectedFriends.push(that.currentUserId);
			console.log("选择人员",selectedFriends);
			that.globalUtil.utilLoading("正在发起群聊...",true);
			let obj={"createUser":that.currentUserId,"chatGroupMembers":selectedFriends};
			let param=Object.assign(obj,newGroup);
			console.log("发起群聊参数",param);
			that.$u.api.chatGroup.launchChatGroup(param).then(res => {	
			  console.log("发起群聊响应结果",res);
			  if (res!=null&&res.data!=null&&res.code===200) {
			        that.globalUtil.utilAlert("创建成功!","success");  
				    that.selectedUser.clear();
					let group=res.data;
					let groupId=group.groupId;
					let timestamp = new Date().getTime();
					let message = {
						"id": new Date().getTime() + "",
						"createTime": that.globalUtil.getTimeStr(timestamp),
						"chatGroupId":groupId,
						"userId": that.vuex_userInfo.id,
						"meFlag": true,
						"userName": that.vuex_userInfo.userName,
						"userAvatar": that.vuex_userInfo.avatar ? that.vuex_userInfo.avatar :
							"/static/image/default/default-user/default-user.png",
						'messageType': that.messageApi.MSG_TYPE.SYSTEM_MSG,
						"contentType": that.messageApi.CONTENT_TYPE.TEXT_CONTENT_TYPE,
						"content": {
							"text":that.vuex_userInfo.userName+'发起了群聊',
						},
						"createTime": that.globalUtil.getTimeStr(timestamp),
						"timestamp": timestamp,
						"platFrom": 1,
						"showTimeFlag": true,
					}
					that.globalWX.sendMessage(message, {
						complete: function(res) {
							if (res == true) {
								uni.switchTab({
									url:'/pages/tabbar/group/group'
								}) 
							} else {
								that.globalUtil.utilAlert("网络故障，稍后重试！");
								return;
							}
						}
					},that.messageApi.BUSINESS_CODE.launchGroup);
				   return;
			  }else{
			    uni.hideLoading();
			    that.globalUtil.utilAlert("发起聊天失败!","error");
			    return;
			  }
			}).catch(res => {
			  uni.hideLoading();
			  that.globalUtil.utilAlert("发起聊天失败!","error");
			  console.log("会话列表加载触发异常",res);
			})
		},
		
		sendSystemMsg:function(chatGroupId){
			let that=this;
			let timestamp=new Date().getTime();
			let message = {
				"id": new Date().getTime() + "",
				"chatGroupId": chatGroupId,
				"userId": that.vuex_userInfo.id,
				"meFlag": true,
				"userName": that.vuex_userInfo.userName,
				"userAvatar": that.vuex_userInfo.avatar ? that.vuex_userInfo.avatar :
					"/static/image/default/default-user/default-user.png",
				'messageType': this.messageApi.MSG_TYPE.SYSTEM_MSG,
				"contentType": this.messageApi.CONTENT_TYPE.TEXT_CONTENT_TYPE,
				"content": {'text':'新建群聊成功'},
				"createTime": that.globalUtil.getTimeStr(timestamp),
				"timestamp": timestamp,
				"platFrom": 'mobile',
				"showTimeFlag": true,
			}
			console.log("发送新建群聊信息", message);
			this.globalWX.sendMessage(message, {
				complete: function(res) {
					console.log("=======已发送==========", res);
					if(res==true){
						let param="?chatGroupId="+chatGroupId;
						let _url="/pages/tabbar/group/chat/chatting";
						let chatUrl=_url+param;
						uni.navigateTo({
						  url: chatUrl,
						  success() {
						
						  }
						});
					}else{
						that.globalUtil.utilAlert("网络故障，稍后重试！");
						return;
					}
				}
			},that.messageApi.BUSINESS_CODE.launchGroup);
		},
		
		
		//跳转个人信息界面
		linkToCard(friend){
			//console.log("跳转朋友信息中心",friend);
			this.$u.route({
			  url: 'pages/chat/friends/friend-home',
			  params:friend,
			})
		}
	},
	onPageScroll(e) {
		this.scrollTop = e.scrollTop;
	}
};
</script>

<style lang="scss" scoped>
.content {
	height: 100%;
	.slot-wrap {
		display: flex;
		align-items: center;
		padding: 0 30rpx; 
	}
	.list-cell {
		display: flex;
		box-sizing: border-box;
		width: 100%;
		padding: 10px 30rpx;
		overflow: hidden;
		color: #323233;
		font-size: 32rpx;
		line-height: 48rpx;
		background-color: #fff;
		align-items: center;
		&-name{
			padding-left: 25rpx;
		}
	}
}
</style>
<style>
	page{
		background-color: #EDEDED;
	}
</style>
